package com.zcsy.manage.web.property;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.model.RequestConstants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.util.DateUtils;
import com.zcsy.manage.model.base.CellHouse;
import com.zcsy.manage.model.base.CellInfo;
import com.zcsy.manage.model.property.CarBill;
import com.zcsy.manage.model.property.CarBillDetail;
import com.zcsy.manage.model.system.Dict;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.service.base.ICellHouseService;
import com.zcsy.manage.service.property.ICarBillDetailService;
import com.zcsy.manage.service.property.ICarBillService;
import com.zcsy.manage.service.system.IDictService;
import com.zcsy.manage.web.common.LogUtils;
import com.zcsy.manage.web.tools.JExcelReport;


/**
 * @Title: CarBillController.java
 * @Package： com.zcsy.manage.web.property
 * @Description: 停车费缴费记录控制层管理类
 * @author xujl
 * @Copyright: 2015 武汉中财数元信息技术有限公司 All rights reserved.
 * @date 2016年4月14日
 * @version 1.0
 * @see JDK1.7.0_75
 * @since
 */
@Controller
@RequestMapping(value = "/carBill")
public class CarBillController {

    @Autowired
    private ICarBillService billService;
    
    @Autowired
    private ICarBillDetailService detailService;
    
    @Autowired
    private ICellHouseService cellHouseService;

    @Autowired
    private IDictService dictService;
    
    /**
     * @Description 根据查询条件分页获取缴费数据列表 
     * @param model
     * @param pNo 当前页
     * @param cellId 小区id 
     * @param regionId 区域id
     * @param buildingId 楼栋id
     * @param unitId 单元id
     * @param houseId 房屋id
     * @param req
     *            用户的请求
     * @return 返回的结果
     * @author xujl
     * @date 2016年4月19日
     * @see 
     */
    @RequestMapping(value = "infoList", method = RequestMethod.GET)
    public String infoList(Model model, Integer pNo, Integer pSize, String regionId,
    		String buildingId, String unitId,String houseId, HttpServletRequest req) {
        if (pNo == null) {
            pNo = Constants.PAGE_NO;
        }

		Integer pageSize;
		if (pSize == null) {
			pageSize = Constants.PAGE_SIZE;
		} else {
			switch (pSize) {
				case 0: pageSize = Constants.PAGE_SIZE;
				break;
				case 1: pageSize = Constants.PAGE_SIZE_TWENTY;
				break;
				case 2: pageSize = Constants.PAGE_SIZE_FIFTY;
				break;
				default:pageSize = Constants.PAGE_SIZE;
				break;
			}
		}
		
        // 此处添加PageHelper将会走拦截器，进行分页，分页方法只针对紧跟着PageHelper的查询方法有效
        PageHelper.startPage(pNo, pageSize);

        CarBill record = new CarBill();

        //获取当前小区id
        User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        String cellId = user.getCurrentCell().getId();
        
        // 标题不为空时，设置标题
        if (StringUtils.isNotEmpty(cellId)) {
            record.setCellId(cellId);
        }
        if (StringUtils.isNotEmpty(regionId)) {
            record.setRegionId(regionId);
        }
        if (StringUtils.isNotEmpty(buildingId)) {
            record.setBuildingId(buildingId);
        }
        if (StringUtils.isNotEmpty(unitId)) {
            record.setUnitId(unitId);
        }
        if (StringUtils.isNotEmpty(houseId)) {
            record.setHouseId(houseId);
        }
        

        List<CarBill> billList = billService.selectByKeyword(record);
        PageInfo<CarBill> info = new PageInfo<CarBill>(billList);
        
//        List<CellInfo> cellInfos = cellInfoService.getAllCellInfo();
        
        List<Dict> dictList = dictService.getDictFromCache("carType");
        model.addAttribute("carType", dictList);

        model.addAttribute("billInfo", info);
        model.addAttribute("currentPage", pNo);
		model.addAttribute("pSize", pSize);
        model.addAttribute("cellId", cellId);
        model.addAttribute("regionId", regionId);
        model.addAttribute("buildingId", buildingId);
        model.addAttribute("unitId", unitId);
        model.addAttribute("houseId", houseId);
        
//        model.addAttribute("cellInfos", cellInfos);

		List<Dict> pageSizes = dictService.getDictFromCache("pageSize");
		model.addAttribute("pageSizes", pageSizes);

        return "property/carbill/billList";
    }

    /**
     * @Description 根据房间号得到账单列表<br>
     * @param houseId
     *            房间号
     * @return 跳转画面URL
     * @author xujl
     * @date 2016年4月14日
     * @see
     */
    @RequestMapping(value = "gotoDetail", method = RequestMethod.GET)
    public String gotoDetail(Model model,String houseId,String carNo) {

        String url = "";
        try {

            List<Dict> payList = dictService.getDictFromCache("payWay");
            model.addAttribute("payWays", payList);
            
            CellHouse house = cellHouseService.selectByPrimaryKey(houseId);
            List<CarBillDetail> detailList = detailService.selectByCarNo(carNo);

            model.addAttribute("house", house);
            model.addAttribute("carNo", carNo);
            model.addAttribute("detailList", detailList);
            url = "property/carbill/billDetail";

        } catch (Exception e) {
        }
        return url;
    }

    /**
     * @Description 根据多个id删除停车费账单信息<br>
     * @param iDs
     *            多个id
     * @param req
     *            用户请求
     * @return 请求结果
     * @author xujl
     * @date 2016年4月14日
     * @see
     */
    @RequestMapping(value = "deleteInfo", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson deleteInfo(String iDs, HttpServletRequest req) {

        RequestJson result = new RequestJson();
        User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);

        try {
            String ids[] = iDs.split("\\,");
            for (int i = 0; i < ids.length; i++ ) {
                billService.deleteByPrimaryKey(ids[i]);
            }
            result.setSuccess(true);
            LogUtils.insertLog("用户删除停车费账单信息", user.getId(), req);

        } catch (NumberFormatException e) {
            result.setSuccess(false);
            result.setMsg("操作失败");
        }
        return result;
    }
    
    /**
     * @Description 导出停车费清单<br>
     * 
     * @param response 
     * @author xujl
     * @date 2016年5月3日
     * @see 
     */
    @RequestMapping("/exportCarBillExcel")
    @ResponseBody
    public void exportCarBillExcel(String regionId, HttpServletRequest request,
            String buildingId, String unitId,String houseId,HttpServletResponse response) {
        List<CarBill> list;
        CarBill record = new CarBill();
        User user = (User)request.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
		String cellId = user.getCurrentCell().getId();

        CellInfo cellInfo = user.getCurrentCell();
        cellId = cellInfo.getId();
        record.setCellId(cellId);
        
        // 标题不为空时，设置标题
        if (StringUtils.isNotEmpty(cellId)) {
            record.setCellId(cellId);
        }
        if (StringUtils.isNotEmpty(regionId)) {
            record.setRegionId(regionId);
        }
        if (StringUtils.isNotEmpty(buildingId)) {
            record.setBuildingId(buildingId);
        }
        if (StringUtils.isNotEmpty(unitId)) {
            record.setUnitId(unitId);
        }
        if (StringUtils.isNotEmpty(houseId)) {
            record.setHouseId(houseId);
        }
        
        try {
            //得到导出的数据列表
            list = billService.selectByKeyword(record);
            
            // 将订单对象转化为到处所需要的数据格式
            Integer type;
            String label;
            if (list.size() > 0) {
                ArrayList<ArrayList<String>> dataList = new ArrayList<ArrayList<String>>();
                int index =1;
                for(CarBill bill : list){
                    ArrayList<String> temp = new ArrayList<String>();
                    //序号
                    temp.add(String.valueOf(index++));
                    temp.add(bill.getId());
                    temp.add(bill.getCellName());
                    temp.add(bill.getRegionName());
                    temp.add(bill.getBuildingName());
                    temp.add(bill.getUnitName());
                    temp.add(bill.getHouseName());
                    temp.add(bill.getCarNo());
                    type = bill.getCarType();
                    if(Constants.SELECT_NONE != type) {
                        label = dictService.selectByFilter(type,"carType").getLabel();
                    } else {
                        label = "未填写";
                    }
                    temp.add(label);
                    dataList.add(temp);
                }
                // 导出标题列
                String[] rows = new String[] {"序号","账单号","小区名","区域名","楼栋名","单元名","房间号","车牌号","车辆类型"};
                // 导出excel文件每列宽度
                int[] style = new int[] {5,20,20,20,20,20,20,20,20};
                // Excel文件sheet名称
                String sheetName = "停车费清单"+DateUtils.getCurrentDate();
                String fileName = "停车费清单";
                doExecl(response,fileName,sheetName, dataList, rows, style);
                LogUtils.insertLog("用户导出停车费账单", user.getId(), request);
            }
        } catch(Exception e) {
            e.printStackTrace();
            return;
        }
    }
    
    /**
     * @Description 通过传入的对象信息集合产生的excel表格<br>
     * @param response 用户响应
     * @param sheetName excel表名称
     * @param dataList 传入的数据列表
     * @param rows excel表的列控制，名称
     * @param style 规定列宽等样式
     * @throws Exception 
     * @author xujl
     * @date 2016年5月3日
     * @see 
     */
    private void doExecl(HttpServletResponse response,String tempName, String sheetName,
            ArrayList<ArrayList<String>> dataList, String[] rows, int[] style) throws Exception {
        //输出的excel名称为中文，否则发生错误
        String tempFileName = tempName+".xls";
        String fileName = new String(tempFileName.getBytes("GB2312"), "ISO_8859_1"); 
        
        ServletOutputStream fout = response.getOutputStream();
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "filename="+fileName+"");
        JExcelReport jexcelOutStream = new JExcelReport();
        try {
            jexcelOutStream.excelreport(sheetName, dataList, rows, fout, style);
            fout.flush();
            fout.close();
        } catch (Exception e){
            e.printStackTrace();
        }
        
    }
}
